package com.abel.demo.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: Abel.lin
 * Date: 2021/6/30 11:21
 * Company: Abel.Studio
 * Description:
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BusinessException.class)
    public Resp catchBusinessException(BusinessException exception, HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        for (StackTraceElement stackTraceElement : exception.getStackTrace()) {
            String s = stackTraceElement.toString();
            if (s.startsWith("com.abel")) {
                sb.append(s).append("\n");
            }
        }
        log.error("uri:{} error, {}:{}\n{}", request.getRequestURI(), exception.getClass().getName(), exception.getMessage(), sb.toString());

        return Resp.failed(exception.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Resp catchException(Exception exception, HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        for (StackTraceElement stackTraceElement : exception.getStackTrace()) {
            String s = stackTraceElement.toString();
            if (s.startsWith("com.abel")) {
                sb.append(s).append("\n");
            }
        }
        log.error("uri:{} error, {}:{}\n{}", request.getRequestURI(), exception.getClass().getName(), exception.getMessage(), sb.toString());
        return Resp.failed(exception.getMessage());
    }
}